<?php
/**
 * 《支出明细》实现类
 *
 * @author 孙晓晔
 * @version $Id: Country.class.php 832 2010-01-06 09:17:14Z xuy $
 */
require_once(dirname(__FILE__) . '/FinanceUtil.class.php');

class OutItem extends FinanceUtil {
	public $tbl = Constant::tbl_cw_out_item;
	
	public $percent = array(
		'-' => '请选择',
		'0.8' => '80%',
		'0.7' => '70%',
		'0.6' => '60%',
		'0.5' => '50%',
		'0.4' => '40%',
		'0.3' => '30%',
		'0.2' => '20%',
		'0.1' => '10%',
		'0.05' => '5%',
	);
	
	public $status = array(
		'-' => '请选择',
		'1' => '申请结算',
		'2' => '等待结算',
		'3' => '正在结算',
		'4' => '完成结算',
		
		'5' => '取消结算',

		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'sign' => '签单日期',
		'date' => '付款日期',
	
		'supplier' => '供应商',
		'emp' => '负责人',
	
		'currency' => '币种',
		'amount' => '金额',		
		'status' => '状态',

		'1' => '创建时间',
		'2' => '更新时间',
	);
	
	public $groupby = array(
		'-' => '请选择',
			
		'office' => '办公区',
		'supplier' => '供应商',
		'emp' => '负责人',
		'currency' => '币种',
		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
		
		$controller->assign_by_ref('percent_option', $this->percent);
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-1 month'));
		
		$controller->display($request, 'finance/out/item/find');
		return true;
	}
	
	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == 'sign') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['sign'];
		}
		
		if ($px == 'date') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['date'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$out_s = $request['out_s'];
		$fk_s = $request['fk_s'];
		$in_item_s = $request['in_item_s'];

		$name_s = $request['name_s'];
		
		$date1_s = $request['date1_s'];
		$date2_s = $request['date2_s'];
		
		$date3_s = $request['date3_s'];
		$date4_s = $request['date4_s'];

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}
		
		if (!empty($out_s)) {
			$where .= $this->_x_s("`out`", $out_s);
		}
		
		if (!empty($fk_s)) {
			$where .= $this->_x_s("fk", $fk_s);
		}
		
		if (!empty($in_item_s)) {
			$where .= $this->_x_s("in_item", $in_item_s);
		}
		
		if (!empty($name_s)) {
			$where .= " AND name LIKE '%" . $name_s . "%'";
		}
				
		if (!empty($date1_s)) {
			$where .= " AND sign >= '" . $date1_s . "'";
		}

		if (!empty($date2_s)) {
			$where .= " AND sign < '" . $date2_s . "'";
		}
		
		if (!empty($date3_s)) {
			$where .= " AND date >= '" . $date3_s . "'";
		}

		if (!empty($date4_s)) {
			$where .= " AND date < '" . $date4_s . "'";
		}
		
		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}

		$emp = $_SESSION['id'];
		
		$p = array('1'=>'149', '2'=>'150', '3'=>'173');
		
		$a = $this->_audit_office($p);
		if (count($a) > 0) {
			$office = implode(",", $a);
			
			return sprintf(" visible = 1 AND (office in (%s) OR emp = '%s' OR oper = '%s')", $office, $emp, $emp);
		}	

		return sprintf(" visible = 1 AND (emp = '%s' OR oper = '%s')", $emp, $emp);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);
		
		$db = newdb($this->dsn_r);
		$where = $this->_where($request);
		$orderby = $this->_orderby();
				
		$fmt = "SELECT * FROM %s a %s %s";
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);		
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {			
			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];				
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'finance/out/item/list');
		return true;
	}

	function xls($controller, $request) {
		$this->pretreat($controller);
		
		$this->findPara($controller, $request);

		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		// $fmt = "SELECT * FROM %s a %s %s LIMIT 20";
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {			
			$row = $this->_view(null, $row);

			$row = $this->_orderby_x($controller, $row, $this->orderby_s);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'finance/out/item/list');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 day'));

		$controller->display($request, 'finance/out/item/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);
				
		$out = $this->_input($request['out']);		
		$supplier = $this->_input($request['supplier']);
		$fk = $this->_input($request['fk']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		
		$name = addslashes($request['name']);
		
		$currency = $request['currency'];
		$total = $request['total'];
		$amount = $request['amount'];
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$sign = $request['sign'];
		$date = $request['date'];
		
		$content = addslashes($request['content']);
		$status = $request['status'];
		
		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, supplier, `out`, fk, name, currency, total, amount, rate, rmb, sign, date, content, emp, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $office, $supplier, $out, $fk, $name, $currency, $total, $amount, $rate, $rmb, $sign, $date, $content, $emp, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);
		
		$request['id_s'] = $db->insert_id();
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/out/item/edit');
		return true;
	}	
	
	function _out($id) {
		require_once(dirname(__FILE__) . '/Out.class.php');
		$aa = new Out();
		
		return $aa->_view($id);
	}
	
	function _mold_code($id) {
		if (empty($id)) {
			return '';
		}

		return Common::code_id(Constant::tbl_cw_out, $id);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);
		
		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$out = $this->_input($request['out']);
		$fk = $this->_input($request['fk']);
		
		$name = addslashes($request['name']);
		
		$currency = $request['currency'];
		$total = $request['total'];
		$amount = $request['amount'];
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$sign = $request['sign'];
		$date = $request['date'];
		
		$content = addslashes($request['content']);
		$status = $request['status'];
		
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET `out` = '%s', fk = '%s', name = '%s', currency = '%s', total = '%s', amount = '%s', rate = '%s', rmb = '%s', sign = '%s', date = '%s', content = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $out, $fk, $name, $currency, $total, $amount, $rate, $rmb, $sign, $date, $content, $status, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function in($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$row['exchange'] = $this->_exchange($row['currency']);

		$controller->assign_by_ref('result', $row);
		
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();
		$aa->_rl_list($controller, $id);

		$controller->display($request, 'finance/out/item/in');
		return true;
	}
	
	function _r_list($in_item) {
		$ret = array();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE in_item = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, $this->tbl, $in_item);
		// debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$ret[] = $row;
		}
		
		return $ret;
	}
	
	function ajax_list($controller, $request) {
		$q = $request['id'];
		
		$data = $this->_x_list($q);
		echo json_encode($data);
	}
	
	function _x_list($out) {
		$ret = array();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE `out` = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, $this->tbl, $out);
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$ret[] = $row;
		}
		
		return $ret;
	}
	
	function inPost($controller, $request) {
		$this->pretreat($controller);
		
		$id = $request['id'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET mold_log = '' WHERE mold_log = '%s'";
		$sql = sprintf($fmt, Constant::tbl_cw_project_log, $id);
		debug($sql);
		$db->query($sql);
		
		$list = $request['list'];
		$bb = explode(',', $list);
		while (list($k, $v) = each($bb)) {
			$fmt = "UPDATE %s SET mold_log = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, Constant::tbl_cw_project_log, $id, $v);
			debug($sql);
			$db->query($sql);
			
			$fmt = "UPDATE %s SET project_log = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, Constant::tbl_cw_mold_log, $v, $id);
			// debug($sql);
			// $db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function profit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();		
		$row['in'] = $aa->_list_out_item($id);
		
		$controller->assign_by_ref('result', $row);
		
		$data = $this->_out($row['out']);		
		$controller->assign_by_ref('out', $data);

		$controller->display($request, 'finance/out/item/profit');
		return true;
	}
	
	function _cost($id) {
		clean($this->tbl . "_id_" . $id);
		$row = $this->id(Constant::tbl_cw_in_item, $id);
		
		return $row['rmb'];
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function profitPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$profit = $request['profit'];
		$content = addslashes($request['content']);
		
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET content = concat(content, '%s'), profit = '%s', modifytime = now() WHERE id = %s";
		$sql = sprintf($fmt, $this->tbl, $content, $profit, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function copy($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/out/item/copy');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		$data = $this->_out($row['out']);		
		$controller->assign_by_ref('out', $data);

		$controller->display($request, 'finance/out/item/view');
		return true;
	}

	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['out_x'] = $this->_out_view($row['out']);
		$row['fk_x'] = $this->_fk_view($row['fk']);
				
		$row['exchange'] = $this->_exchange($row['currency']);		

		$row = $this->_view_t($row);
		
		$row['mold_x'] = $row['mold'] . ":" . $row['mold_t'];

		return $row;
	}
	
	function _out_view($id) {
		require_once(dirname(__FILE__) . '/Out.class.php');
		$aa = new Out();
	
		return $aa->_view($id);
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('308');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '支出明细';

		$cc = array(
			'签单信息'=>array('w' => "DATE_FORMAT(sign, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),
			'已付信息'=>array('w' => "DATE_FORMAT(date, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}

		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'finance/out/item/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function tjw($controller, $request) {
		$bb = $this->_list_email('308');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '支出明细（周报）';

		$cc = array(
			'签单信息'=>array('w' => "DATE_FORMAT(sign, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),
			'已付信息'=>array('w' => "DATE_FORMAT(date, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE status = '1' AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE status = '1' AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE status = '1' AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE status = '1' AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE status = '1' AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "WHERE status = '1'")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'finance/out/item/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
		
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'currency';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, SUM(total*rate) AS c, SUM(total) AS d FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, SUM(total*rate) AS c, SUM(total) AS d FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
	
	function _fk_view($id) {
		if (empty($id)) {
			return false;
		}
		
		require_once(dirname(__FILE__) . '/Payment.class.php');
		$aa = new Payment();
		
		return $aa->_view($id);
	}
	
	function _count($id, $status = 'all') {
		$ret = array();
	
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT COUNT(*) t FROM %s WHERE `out` = '%s' AND visible = '1' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT COUNT(*) t FROM %s WHERE `out` = '%s' AND visible = '1' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}
		// debug($sql);
		$result = $db->query($sql);
		$row = $db->fetch_array($result);
		
		return $row['t'];
	}
	
	function _list($id, $status = 'all') {
		$ret = array();
		
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE `out` = '%s' AND visible = '1' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE `out` = '%s' AND visible = '1' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}		
		// debug($sql);
		$result = $db->query($sql);		
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);			
			$row['ok'] = true;			

			$ret[] = $row;
		}

		return $ret;
	}
	
	function _list_in_item($id) {
		$ret = array();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE `in_item` = '%s' ORDER BY id";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$ret[] = $row;
		}

		return $ret;
	}
	
	function _list_status($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE `out` = '%s' ORDER BY status";
		$sql = sprintf($fmt, $this->tbl, $id);
		// debug($sql);
		$result = $db->query($sql);
		$ret = 9;
		while ($row = $db->fetch_array($result)) {
			$ret = ($ret < $row['status']) ? $ret : $row['status'];
		}
	
		return $ret;
	}
	
	function _insert($request) {
		
		$id = $request['id'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$supplier = $this->_input($request['supplier']);
		$supplier_x = addslashes($request['supplier_x']);
		
		$mold = $this->_input($request['mold']);
		$type = $request['type'];
		
		$currency = $request['currency'];
		$rate = $this->_exchange($currency);
		
		$data = json_decode($request['item'], true);
		
		$db = newdb($this->dsn_w);		
		$fmt = "INSERT INTO %s(office, emp, `out`, mold, name, currency, total, amount, rate, rmb, content, oper, status, createtime, modifytime) ";
		$fmt .= "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '2', now(), now())";
		while (list($k, $v) = each($data)) {
			
			if (empty($v['name']) && empty($v['total'])) {
				continue;
			}
			
			$a = $this->_input($v['mold_x']);
			if (!empty($a)) {
				$mold = $a;
			}
			
			$name = addslashes($v['name']);			
			if (empty($name)) {
				continue;
			}
			
			$rmb = $v['total'] * $rate;
						
			$content = addslashes($v['content']);
			
			$sql = sprintf($fmt, $this->tbl, $office, $emp, $id, $mold, $name, $currency, $v['total'], $v['total'], $rate, $rmb, $content, $_SESSION['id']);
			debug($sql);
			$db->query($sql);
		}
		
		$fmt = "UPDATE %s SET supplier = '%s' WHERE `out` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $supplier, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _update($request) {
		
		$id = $request['id'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$supplier = $this->_input($request['supplier']);
		$supplier_x = addslashes($request['supplier_x']);
		
		$mold = $this->_input($request['mold']);
		$type = $request['type'];
		
		$currency = $request['currency'];
		$rate = $this->_exchange($currency);
		
		$data = json_decode($request['item'], true);
		
		$db = newdb($this->dsn_w);		
		while (list($k, $v) = each($data)) {
			
			$a = $this->_input($v['mold_x']);
			if (!empty($a)) {
				$mold = $a;
			}
			
			$name = addslashes($v['name']);
			$content = addslashes($v['content']);
			
			$rmb = $v['total'] * $rate;
				
			if (array_key_exists("createtime", $v)) {
				if ($v['status'] == 4) {
					continue;
				}
				
				if (!$this->_ok($v['ok'])) {
					// $fmt = "DELETE FROM %s WHERE id = '%s'";
					$fmt = "UPDATE %s SET visible = '2', modifytime = now()  WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $v['id']);
				} else {
					clean($this->tbl . "_id_" . $v['id']);
														
					$fmt = "UPDATE %s SET office = '%s', dept = '%s', emp = '%s', mold = '%s', name = '%s', total = '%s', amount = '%s', currency = '%s', rate = '%s', rmb = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $mold, $name, $v['total'], $v['total'], $currency, $rate, $rmb, $content, $v['id']);
				}			
			} else {
				if (!$this->_ok($v['ok'])) {
					continue;
				}
			
				$fmt = "INSERT INTO %s(office, dept, emp, `out`, mold, name, currency, total, amount, rate, rmb, content, oper, status, createtime, modifytime) ";
				$fmt .= "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '2', now(), now())";
				$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $id, $mold, $name, $currency, $v['total'], $v['total'], $rate, $rmb, $content, $_SESSION['id']);			
			}
			
			debug($sql);
			$db->query($sql);
		}
		
		$fmt = "UPDATE %s SET supplier = '%s' WHERE `out` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $supplier, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _update_list($in_item, $list) {
		$ret = array();
		
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET in_item = '' WHERE in_item = '%s'";
		$sql = sprintf($fmt, $this->tbl, $in_item);
		$db->query($sql);		
		if (empty($list)) {
			return $ret;
		}
		
		$bb = explode(',', $list);
		while (list($k, $id) = each($bb)) {			
			$fmt = "UPDATE %s SET in_item = '%s', modifytime = NOW() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $in_item, $id);
			debug($sql);
			$db->query($sql);
		}
		
		return $ret;
	}
	
	function _update_status_3($in_item) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET status = '3' WHERE status = '2' AND in_item = '%s'";
		$sql = sprintf($fmt, $this->tbl, $in_item);
		$db->query($sql);
	}
	
	function _insert_my($id, $log, $emp) {
		$emp = $_SESSION['id'];
		
		$db = newdb($this->dsn_w);		
		$fmt = "INSERT INTO %s(mold, `item`, total, amount, currency, content, emp, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		while (list($k, $v) = each($log)) {
			if (!$this->_ok($v['ok'])) {
				continue;
			}
			
			$sql = sprintf($fmt, $this->tbl, $id, $v['item'], $v['total'], $v['amount'], $v['currency'], $v['content'], $emp, $emp);
			debug($sql);
			$db->query($sql);
		}
	}
	
	function _update_my($id, $log, $emp) {
		$emp = $_SESSION['id'];
		
		$db = newdb($this->dsn_w);		
		while (list($k, $v) = each($log)) {	
			if (array_key_exists("createtime", $v)) {
				if ($v['status'] > 1) {
					continue;
				}
					
				if (!$this->_ok($v['ok'])) {
					$fmt = "DELETE FROM %s WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $v['id']);
				} else {									
					$fmt = "UPDATE %s SET item = '%s', total = '%s', amount = '%s', currency = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $v['item'], $v['total'], $v['amount'], $v['currency'], $v['content'], $v['id']);
				}			
			} else {
				if (!$this->_ok($v['ok'])) {
					continue;
				}
				
				$fmt = "INSERT INTO %s(mold, `item`, total, amount, currency, content, emp, oper, createtime, modifytime)";
				$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
				$sql = sprintf($fmt, $this->tbl, $id, $v['item'], $v['total'], $v['amount'], $v['currency'], $v['content'], $emp, $_SESSION['id']);			
			}
			
			debug($sql);
			$db->query($sql);
		}
	}
	
	function finish($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$controller->assign_by_ref('result', $row);
		
		$controller->assign_by_ref('fk_option', $this->_fk($row['supplier']));
		
		$controller->display($request, 'finance/out/item/finish');
		return true;
	}
	
	function _fk($supplier) {
		require_once(dirname(__FILE__) . '/Payment.class.php');
		$aa = new Payment();
		
		return $aa->_list_2($supplier);
	}
	
	function _update_finish($fk, $finish) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET date = '%s', status = '4' WHERE fk = '%s'";
		$sql = sprintf($fmt, $this->tbl, $finish, $fk);
		$db->query($sql);
	}
	
	function finishPost($controller, $request) {
		$this->pretreat($controller);
		
		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$fk = $request['fk'];
		$sign = $request['sign'];
		
		$amount = $request['amount'];		
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		$content = addslashes($request['content']);
		
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET fk = '%s', sign = '%s', amount = '%s', rate = '%s', rmb = '%s', content = '%s', status = '3', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $fk, $sign, $amount, $rate, $rmb, $content, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function batch_begin($controller, $request) {
		$this->pretreat($controller);
		
		$insql = "in ('000000000";
		while (list($k, $v) = each($request)) {
			if (substr($k, 0, 2) == "c_") {
				$insql .= "', '" . $v;
			}
		}
		$insql .= "')";
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id %s";
		$sql = sprintf($fmt, $this->tbl, $insql);
		debug($sql);
		
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'finance/out/item/batch_begin');
		return true;
	}
	
	function batch_beginPost($controller, $request) {
		$this->pretreat($controller);
		
		$content = addslashes($request['content']);
		$status = $request['status'];

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request['cc'])) {
			$fmt = "UPDATE %s SET content = concat(content, '%s'), status = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $content, $status, $id);
			debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function batch_sign($controller, $request) {
		$this->pretreat($controller);
				
		$insql = "in ('000000000";
		while (list($k, $v) = each($request)) {
			if (substr($k, 0, 2) == "c_") {
				$insql .= "', '" . $v;
			}
		}
		$insql .= "')";
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id %s";
		$sql = sprintf($fmt, $this->tbl, $insql);
		debug($sql);
		
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$controller->assign_by_ref('fk_option', $this->_fk($data[0]['supplier']));

		$controller->display($request, 'finance/out/item/batch_sign');
		return true;
	}
	
	function batch_signPost($controller, $request) {
		$this->pretreat($controller);
		
		$fk = $request['fk'];
		$sign = $request['sign'];
		$content = addslashes($request['content']);
		$status = $request['status'];

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request['cc'])) {
			$fmt = "UPDATE %s SET fk = '%s', sign = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $fk, $sign, $id);
			debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
		
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
			
			$row = $this->id($this->tbl, $id);
			
			if ($this->_is_delete($row)) {
				$fmt = "DELETE FROM %s WHERE id = '%s'";
				$sql = sprintf($fmt, $this->tbl, $id);
				// debug($sql);
				$db->query($sql);
			}
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}

		if ($row['status'] > 1) {
			return false;
		}

		if ($this->_audit('77')) {
			return true;
		}

		if ($row['oper'] == $_SESSION['id']) {
			return true;
		}

		return false;
	}
	
	function group($controller, $request) {
		$this->pretreat_group($controller);

		// $controller->assign('t1', strtotime('-1 month'));
		// $controller->assign('t2', strtotime('+1 day'));

		$num = array(
			'1' => '按次数',
			'2' => '按本币金额',
			'3' => '按人民币',
		);
		$controller->assign('num_option', $num);

		$controller->display($request, 'finance/out/item/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function groupby_dd($px) {
		if ($px == '1') {
			return "DATE_FORMAT(date, '%Y-%m-%d %H')";
		}

		if ($px == '2') {
			return "DATE_FORMAT(date, '%Y-%m-%d')";
		}

		if ($px == '3') {
			return "DATE_FORMAT(date, '%Y-%m')";
		}

		return $px;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$num_s = $request['num_s'];
		if (!empty($num_s) && $num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(total) AS c FROM %s a ";
		} else if ($num_s == '3') {
			$fmt = "SELECT %s AS a, SUM(rmb) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(total) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}
	
	function _delete_out($id) {
		$db = newdb($this->dsn_w);
		$fmt = "DELETE FROM %s WHERE mold = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		// debug($sql);
		$db->query($sql);
	}
	
	function _list_fk($id, $status = 'all') {
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE `fk` = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE `fk` = '%s' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {			
			$row = $this->_view(null, $row);
			
			$row['ok'] = true; 

			$ret[] = $row;
		}
		
		return $ret;
	}
		
	function _tj_a($controller, $request) {	
		$s = $this->groupby($controller, $this->groupby_s);
		$df = "DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')";

		$fmt = "SELECT %s as a, SUM(amount) as c FROM %s a WHERE date >= %s GROUP BY %s ORDER BY c DESC";
		$sql = sprintf($fmt, $s, $this->tbl, $df, $s);
		echo $sql . "\n";

		$this->_group_tj($controller, $sql);

		return $controller->sunxy($request, 'tj_a');
	}
	
	function sync($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE fk > 0";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		
		while ($row = $db->fetch_array($result)) {
			$fk = Common::id(Constant::tbl_cw_payment, $row['fk']);
			if ($fk['status'] <> '4') {
				continue;
			}
			
			$fmt = "UPDATE %s SET date = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $fk['finish'], $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function z($controller, $request) {
		
		require_once(dirname(__FILE__) . '/Out.class.php');
		$aa = new Out();
		
		$df = "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY)";
		$db = newdb($this->dsn_r);
		$fmt = "SELECT `out` FROM %s WHERE status = 3 AND %s GROUP BY `out`";
		// $fmt = "SELECT `out` FROM %s WHERE status = 3 GROUP BY `out`";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if ($this->_in_item($row['out'])) {
				continue;
			}
			
			$aa->_update_status_3($row['out']);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function _in_item($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE `out` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if ($row['status'] < 3) {
				return true;
			}
		}
		
		return false;
	}
	
	function move($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
	
	function b($controller, $request) {
		require_once(dirname(__FILE__) . '/Out.class.php');
		$aa = new Out();
		
		$t1 = date("Y-m-d", strtotime('-1 month'));
		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE modifytime > '%s' GROUP BY `out`";
		$sql = sprintf($fmt, $this->tbl, $t1);
		// echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if ($this->_b2($aa, $row['out'])) {
				echo "U";
			} else {
				echo ".";
			}
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function _b2($aa, $out) {		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT status, COUNT(*) t FROM %s WHERE `out` = '%s' GROUP BY status ORDER BY t, status";
		$sql = sprintf($fmt, $this->tbl, $out);
		// echo $sql . "\n";
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {			
			return $aa->_u2($out, $row['status']);
		}
		
		return false;
	}
}
?>